package com.dsl.service;

import com.dsl.dao.CommentMapper;
import com.dsl.entity.Comment;
import com.dsl.utils.CommunityConstant;
import com.dsl.utils.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * @Description 评论业务类
 * @Author dsl
 * @Date 2024/9/10 上午9:23
 * @Version 1.0
 */
@Service
public class CommentService implements CommunityConstant {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private DiscussPostService discussPostService;

    //根据实体对象查询评论
    public List<Comment> getCommentByEntity(int entityType, int entityId, int offset, int limit){
        return commentMapper.getCommentByEntity(entityType, entityId, offset, limit);
    }

    //查询评论数量
    public int getCommentCount(int entityType, int entityId){
        return commentMapper.getCommentCountByEntity(entityType, entityId);
    }


    //添加评论
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if(comment == null){
            throw new IllegalArgumentException("参数不能为空！");
        }

        //更新帖子评论数量
        if(comment.getEntityType() == ENTITY_TYPE_POST){
            int count = commentMapper.getCommentCountByEntity(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count + 1);
        }

        //添加评论实体
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.addComment(comment);

        return rows;
    }

    //根据id查询评论
    public Comment getCommentById(int id){

        return commentMapper.getCommentById(id);
    }

}
